const passport =require('koa-passport')

const User = require('../models/user')

module.exports.login = async (ctx, next) => {
  return passport.authenticate('local',
    function(err, user, info, status) {
      const token = user.generateToken()
      const response = user.toJSON()
      delete response.password
      ctx.body = {
        token,
        user: response
      }
      return ctx.login({id: user._id, username: user.username, password: user.password})
  })(ctx, next)
}

module.exports.logout = async (ctx, next) => {
  ctx.logout()
  ctx.body = {auth: ctx.isAuthenticated(), user: ctx.state.user}
}

module.exports.auth = async (ctx, next) => {
  if(ctx.isAuthenticated()) {
     next()
   } else {
    ctx.status = 401
    ctx.body = {
      msg: 'auth fail'
    }
  }
}

module.exports.authUser = async (ctx, next) => {
  return passport.authenticate('bearer',{ session: false },
    function(err, user) {
      ctx.login({id: user.id, username: user.username})
      next()
  })(ctx, next)
}

